package com.ccjk.beusoft.hot.surface;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Created by CCJK on 2017/12/26.
 */

public class MyView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    private final Thread thread;
    private SurfaceHolder holder;
    private boolean isLoop;
    private Canvas canvas;
    private Paint paint;

    public MyView(Context context) {
        this(context, null);
    }

    public MyView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setFocusable(true);
        setFocusableInTouchMode(true);
        this.setKeepScreenOn(true);

        thread = new Thread(this);
        holder = getHolder();
        holder.addCallback(this);
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);
        paint.setTextSize(50);
//        setBackgroundColor(Color.GREEN);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isLoop = true;
        thread.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isLoop = false;
    }

    private int flag = 0;



    @Override
    public void run() {
        while (isLoop) {
            try {
                canvas = holder.lockCanvas();
                paint.setColor(Color.WHITE);
                canvas.drawRect(0,0,canvas.getWidth(),canvas.getHeight(),paint);
                paint.setColor(Color.RED);
                canvas.drawRect(0,100,100,300,paint);
                canvas.drawText(flag + "", canvas.getWidth() / 2, canvas.getHeight() / 2, paint);
                flag++;
            } catch (Exception e) {
                Log.e("surfaceview", "1", e);
            } finally {
                if (canvas != null) {
                    holder.unlockCanvasAndPost(canvas);
                    canvas = null;
                }
            }
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                Log.e("surfaceview", "2", e);
            }

        }

    }
}
